<template>
  <div class="video-monitor-container">
    <!-- 顶部操作栏 -->
    <div class="top-toolbar">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-card shadow="never" class="toolbar-card">
            <div class="toolbar-content">
              <div class="toolbar-left">
                <el-button type="primary" icon="Refresh" @click="loadTreeData">
                  刷新
                </el-button>
                <el-button type="success" icon="VideoPlay" @click="showPlaybackDialog">
                  历史回放
                </el-button>
                <el-button type="warning" icon="Warning" @click="showAlarmDialog">
                  告警列表
                </el-button>
              </div>

              <div class="toolbar-right">
                <el-input v-model="searchKeyword" placeholder="搜索设备名称/编号" clearable style="width: 200px;"
                  @keyup.enter="loadTreeData">
                  <template #append>
                    <el-button icon="Search" @click="loadTreeData" />
                  </template>
                </el-input>

                <el-select v-model="filterStatus" placeholder="状态筛选" clearable @change="loadTreeData"
                  style="width: 120px;">
                  <el-option label="全部状态" value="" />
                  <el-option label="在线" value="1" />
                  <el-option label="离线" value="2" />
                  <el-option label="故障" value="3" />
                </el-select>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 主要内容区 -->
    <el-row :gutter="20" class="main-content">
      <!-- 左侧设备树 -->
      <el-col :xs="24" :sm="8" :md="6" :lg="5" :xl="4">
        <el-card shadow="never" class="tree-card">
          <template #header>
            <div class="card-header">
              <span>监控设备树</span>
              <el-button link icon="Refresh" @click="loadTreeData" />
            </div>
          </template>

          <div class="tree-container">
            <el-tree ref="treeRef" :data="treeData" :props="treeProps" :filter-node-method="filterNode" node-key="id"
              highlight-current :expand-on-click-node="false" @node-click="handleNodeClick" v-loading="treeLoading">
              <template #default="{ node, data }">
                <div class="tree-node">
                  <span class="node-label">{{ node.label }}</span>
                  <el-tag v-if="data.type === 'DEVICE'" :type="getStatusTagType(data.status)" size="small">
                    {{ getStatusText(data.status) }}
                  </el-tag>
                  <el-tag v-if="data.code" type="info" size="small">
                    {{ data.code }}
                  </el-tag>
                </div>
              </template>
            </el-tree>
          </div>
        </el-card>
      </el-col>

      <!-- 中间视频监控区 -->
      <el-col :xs="24" :sm="16" :md="18" :lg="19" :xl="20">
        <el-card shadow="never" class="video-card">
          <template #header>
            <div class="card-header">
              <span>视频监控</span>
              <div class="header-actions">
                <span v-if="currentDevice" class="device-info">
                  {{ currentDevice.deviceName }} ({{ currentDevice.deviceCode }})
                  <el-tag :type="getStatusTagType(currentDevice.deviceStatus)" size="small">
                    {{ getStatusText(currentDevice.deviceStatus) }}
                  </el-tag>
                </span>
                <el-button v-if="currentDevice" type="primary" icon="VideoPlay"
                  @click="showPlaybackDialog(currentDevice)">
                  回放
                </el-button>
              </div>
            </div>
          </template>

          <div class="video-content">
            <div v-if="currentStream" class="video-player">
              <!-- <video ref="videoPlayer" :src="currentStream.streamUrl" controls autoplay muted
                style="width: 100%; height: 100%;">
                您的浏览器不支持视频播放
              </video> -->

              <el-descriptions :column="2" border size="small">
                <el-descriptions-item label="编码格式">{{ currentStream.streamCodec }}</el-descriptions-item>
                <el-descriptions-item label="分辨率">{{ currentStream.streamResolution }}</el-descriptions-item>
                <el-descriptions-item label="码率">{{ currentStream.streamBitrate }} kbps</el-descriptions-item>
                <el-descriptions-item label="状态">
                  <el-tag :type="getStatusTagType(currentStream.deviceStatus)" size="small">
                    {{ getStatusText(currentStream.deviceStatus) }}
                  </el-tag>
                </el-descriptions-item>
              </el-descriptions>
              <!-- <LivePlayer src="currentStream.streamUrl" protocol="hls" /> -->

            </div>

            <div v-else class="video-placeholder">
              <el-empty description="请选择设备查看视频" :image-size="100" />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 底部状态栏 -->
    <div class="bottom-status-bar">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-card shadow="never" class="status-card">
            <div class="status-content">
              <div class="status-left">
                <span class="status-text">
                  已连接设备:
                  <el-tag type="success" size="small">{{ statusSummary.online || 0 }}</el-tag>
                  /
                  <el-tag type="info" size="small">{{ statusSummary.total || 0 }}</el-tag>
                  路
                </span>
                <span class="status-text">
                  离线:
                  <el-tag type="danger" size="small">{{ statusSummary.offline || 0 }}</el-tag>
                </span>
                <span class="status-text">
                  故障:
                  <el-tag type="warning" size="small">{{ statusSummary.fault || 0 }}</el-tag>
                </span>
              </div>

              <div class="status-right">
                <span class="alarm-info" @click="showAlarmDialog" style="cursor: pointer;">
                  <el-icon>
                    <Warning />
                  </el-icon>
                  告警: {{ alarmSummary.totalCount || 0 }} 条
                  <span v-if="alarmSummary.latest" class="latest-alarm">
                    最新: {{ formatTime(alarmSummary.latest?.alarmTime) }}
                  </span>
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 历史回放弹窗 -->
    <el-dialog title="历史回放" v-model="playbackDialogVisible" width="80%" top="5vh" :close-on-click-modal="false">
      <div class="playback-dialog">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="never" class="playback-sidebar">
              <template #header>
                <div class="card-header">
                  <span>设备选择</span>
                </div>
              </template>

              <div class="device-search">
                <el-input v-model="deviceSearchKeyword" placeholder="搜索设备" clearable @keyup.enter="loadDeviceList">
                  <template #append>
                    <el-button icon="Search" @click="loadDeviceList" />
                  </template>
                </el-input>
              </div>

              <div class="device-list">
                <el-table :data="deviceList" v-loading="deviceLoading" highlight-current-row
                  @row-click="selectPlaybackDevice" height="300">
                  <el-table-column prop="deviceName" label="设备名称" min-width="120" show-overflow-tooltip />
                  <el-table-column prop="deviceCode" label="设备编号" width="100" />
                  <el-table-column label="状态" width="80" align="center">
                    <template #default="{ row }">
                      <el-tag :type="getStatusTagType(row.deviceStatus)" size="small">
                        {{ getStatusText(row.deviceStatus) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-card>
          </el-col>

          <el-col :span="18">
            <el-card shadow="never" class="playback-content">
              <template #header>
                <div class="card-header">
                  <span>回放记录</span>
                  <div class="header-actions">
                    <el-date-picker v-model="playbackDateRange" type="daterange" range-separator="至"
                      start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"
                      @change="loadStorageList" />
                    <el-button type="primary" icon="Search" @click="loadStorageList">查询</el-button>
                  </div>
                </div>
              </template>

              <div class="storage-list">
                <el-table :data="storageList" v-loading="storageLoading" height="300">
                  <el-table-column prop="startTime" label="开始时间" width="160">
                    <template #default="{ row }">
                      {{ formatTime(row.startTime) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="endTime" label="结束时间" width="160">
                    <template #default="{ row }">
                      {{ formatTime(row.endTime) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="fileSize" label="文件大小" width="100">
                    <template #default="{ row }">
                      {{ formatFileSize(row.fileSize) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="storagePath" label="存储路径" show-overflow-tooltip />
                  <el-table-column label="操作" width="120" fixed="right" align="center">
                    <template #default="{ row }">
                      <el-button type="primary" size="small" @click="playStorage(row)">播放</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <div class="playback-player" v-if="currentStorage">
                <video ref="playbackPlayer" :src="currentStorage.storagePath" controls
                  style="width: 100%; height: 300px;">
                  您的浏览器不支持视频播放
                </video>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <template #footer>
        <el-button @click="playbackDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 告警列表弹窗 -->
    <el-dialog title="告警列表" v-model="alarmDialogVisible" width="70%" top="5vh">
      <div class="alarm-dialog">
        <el-table :data="alarmList" v-loading="alarmLoading" height="400">
          <el-table-column prop="alarmTime" label="告警时间" width="160">
            <template #default="{ row }">
              {{ formatTime(row.alarmTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="deviceName" label="设备名称" width="120" />
          <el-table-column prop="location" label="位置" width="200" show-overflow-tooltip />
          <el-table-column label="操作" width="120" fixed="right" align="center">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="viewAlarmReplay(row)">查看回放</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <el-button @click="alarmDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 告警回放弹窗 -->
    <el-dialog :title="`告警回放 - ${currentAlarm?.deviceName || ''}`" v-model="alarmReplayDialogVisible" width="60%"
      top="10vh">
      <div v-if="currentAlarmReplay" class="alarm-replay-dialog">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="设备名称">{{ currentAlarmReplay.deviceName }}</el-descriptions-item>
          <el-descriptions-item label="站点路径">{{ currentAlarmReplay.stationPath }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatTime(currentAlarmReplay.startTime) }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ formatTime(currentAlarmReplay.endTime) }}</el-descriptions-item>
          <el-descriptions-item label="存储路径" :span="2">{{ currentAlarmReplay.storagePath }}</el-descriptions-item>
        </el-descriptions>

        <div class="replay-player" v-if="currentAlarmReplay.storagePath">
          <video ref="alarmPlayer" :src="currentAlarmReplay.storagePath" controls
            style="width: 100%; height: 300px; margin-top: 20px;">
            您的浏览器不支持视频播放
          </video>
        </div>

        <div v-else class="no-video-info">
          <el-alert type="info" title="暂无录像文件" show-icon>
            该告警发生时未生成录像文件
          </el-alert>
        </div>
      </div>

      <template #footer>
        <el-button @click="alarmReplayDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Warning } from '@element-plus/icons-vue'
// import LivePlayer from '@/components/LivePlayer'
// API导入
import {
  getMonitorTree,
  getVideoStream,
  getVideoStorageList,
  getAlarmSummary,
  getAlarmLatest,
  getAlarmReplay,
  getDeviceStatusSummary,
  getMonitorDeviceList
} from '@/api/prod_operate/security/video_display'

// 响应式数据
const treeLoading = ref(false)
const streamLoading = ref(false)
const deviceLoading = ref(false)
const storageLoading = ref(false)
const alarmLoading = ref(false)
const treeData = ref([])
const deviceList = ref([])
const storageList = ref([])
const alarmList = ref([])
const currentDevice = ref(null)
const currentStream = ref(null)
const currentStorage = ref(null)
const currentAlarm = ref(null)
const currentAlarmReplay = ref(null)
const searchKeyword = ref('')
const deviceSearchKeyword = ref('')
const filterStatus = ref('')
const playbackDateRange = ref([])

// 弹窗控制
const playbackDialogVisible = ref(false)
const alarmDialogVisible = ref(false)
const alarmReplayDialogVisible = ref(false)

// 状态数据
const statusSummary = reactive({
  total: 0,
  online: 0,
  offline: 0,
  fault: 0
})

const alarmSummary = reactive({
  totalCount: 0,
  latest: null
})

// 树配置
const treeProps = {
  label: 'label',
  children: 'children'
}

// 生命周期
onMounted(() => {
  loadTreeData()
  loadStatusSummary()
  loadAlarmSummary()
})

// 监听搜索关键词变化
watch(searchKeyword, (val) => {
  if (treeRef.value) {
    treeRef.value.filter(val)
  }
})

// 方法定义
const loadTreeData = async () => {
  try {
    treeLoading.value = true
    const params = {
      keyword: searchKeyword.value,
      status: filterStatus.value
    }

    const res = await getMonitorTree(params)
    if (res.code === 200) {
      treeData.value = [res.data]
    } else {
      ElMessage.error(res.msg || '加载失败')
    }
  } catch (error) {
    ElMessage.error('网络错误')
  } finally {
    treeLoading.value = false
  }
}

const loadStatusSummary = async () => {
  try {
    const res = await getDeviceStatusSummary()
    if (res.code === 200) {
      Object.assign(statusSummary, res.data)
    }
  } catch (error) {
    console.error('加载状态汇总失败:', error)
  }
}

const loadAlarmSummary = async () => {
  try {
    const res = await getAlarmSummary()
    if (res.code === 200) {
      Object.assign(alarmSummary, res.data)
    }
  } catch (error) {
    console.error('加载告警汇总失败:', error)
  }
}

const loadDeviceList = async () => {
  try {
    deviceLoading.value = true
    const params = {
      keyword: deviceSearchKeyword.value
    }

    const res = await getMonitorDeviceList(params)
    if (res.code === 200) {
      deviceList.value = res.data
    } else {
      ElMessage.error(res.msg || '加载失败')
    }
  } catch (error) {
    ElMessage.error('网络错误')
  } finally {
    deviceLoading.value = false
  }
}

const loadStorageList = async () => {
  if (!currentDevice.value) {
    ElMessage.warning('请先选择设备')
    return
  }

  try {
    storageLoading.value = true
    const params = {
      deviceId: currentDevice.value.deviceId
    }

    if (playbackDateRange.value && playbackDateRange.value.length === 2) {
      params.startTime = playbackDateRange.value[0]
      params.endTime = playbackDateRange.value[1]
    }

    const res = await getVideoStorageList(params)
    if (res.code === 200) {
      storageList.value = res.data
    } else {
      ElMessage.error(res.msg || '加载失败')
    }
  } catch (error) {
    ElMessage.error('网络错误')
  } finally {
    storageLoading.value = false
  }
}

const loadAlarmList = async () => {
  try {
    alarmLoading.value = true
    const res = await getAlarmLatest({ limit: 50 })
    if (res.code === 200) {
      alarmList.value = res.data
    } else {
      ElMessage.error(res.msg || '加载失败')
    }
  } catch (error) {
    ElMessage.error('网络错误')
  } finally {
    alarmLoading.value = false
  }
}

const handleNodeClick = async (data) => {
  if (data.type === 'DEVICE') {
    currentDevice.value = data
    await loadVideoStream(data.id)
  }
}

const loadVideoStream = async (deviceId) => {
  try {
    streamLoading.value = true
    const res = await getVideoStream({ deviceId })
    if (res.code === 200) {
      currentStream.value = res.data
    } else {
      ElMessage.error(res.msg || '加载视频流失败')
      currentStream.value = null
    }
  } catch (error) {
    ElMessage.error('网络错误')
    currentStream.value = null
  } finally {
    streamLoading.value = false
  }
}

const showPlaybackDialog = (device) => {
  playbackDialogVisible.value = true
  if (device) {
    currentDevice.value = device
  }
  loadDeviceList()
}

const showAlarmDialog = async () => {
  alarmDialogVisible.value = true
  await loadAlarmList()
}

const selectPlaybackDevice = (device) => {
  currentDevice.value = device
  loadStorageList()
}

const playStorage = (storage) => {
  currentStorage.value = storage
}

const viewAlarmReplay = async (alarm) => {
  currentAlarm.value = alarm
  try {
    const res = await getAlarmReplay({ alarmId: alarm.alarmId })
    if (res.code === 200) {
      currentAlarmReplay.value = res.data
      alarmReplayDialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '加载回放信息失败')
    }
  } catch (error) {
    ElMessage.error('网络错误')
  }
}

// 工具函数
const filterNode = (value, data) => {
  if (!value) return true
  return data.label.includes(value) || (data.code && data.code.includes(value))
}

const getStatusTagType = (status) => {
  const types = {
    1: 'success', // 在线
    2: 'danger',  // 离线
    3: 'warning'   // 故障
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    1: '在线',
    2: '离线',
    3: '故障'
  }
  return texts[status] || '未知'
}

const formatTime = (time) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const formatFileSize = (size) => {
  if (!size) return '-'
  if (size < 1024) {
    return size + ' KB'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' MB'
  } else {
    return (size / (1024 * 1024)).toFixed(2) + ' GB'
  }
}
</script>

<style scoped>
.video-monitor-container {
  padding: 20px;
  height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

/* 顶部工具栏 */
.top-toolbar {
  margin-bottom: 20px;
}

.toolbar-card {
  border: none;
}

.toolbar-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.toolbar-left {
  display: flex;
  gap: 10px;
}

.toolbar-right {
  display: flex;
  gap: 10px;
  align-items: center;
}

/* 主要内容区 */
.main-content {
  flex: 1;
  min-height: 0;
  margin-bottom: 20px;
}

.tree-card,
.video-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  border: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.device-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 树形结构 */
.tree-container {
  flex: 1;
  overflow-y: auto;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
}

.node-label {
  flex: 1;
}

/* 视频内容 */
.video-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-player {
  width: 100%;
  height: 100%;
  position: relative;
}


.video-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 底部状态栏 */
.bottom-status-bar {
  margin-top: auto;
}

.status-card {
  border: none;
}

.status-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.status-text {
  display: flex;
  align-items: center;
  gap: 5px;
}

.status-right {
  display: flex;
  align-items: center;
}

.alarm-info {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #e6a23c;
  font-weight: 500;
}

.latest-alarm {
  font-size: 12px;
  color: #909399;
}

/* 弹窗样式 */
.playback-dialog,
.alarm-dialog {
  height: 60vh;
}

.playback-sidebar,
.playback-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.device-search {
  margin-bottom: 15px;
}

.device-list,
.storage-list {
  flex: 1;
}

.playback-player {
  margin-top: 20px;
  border-top: 1px solid #e4e7ed;
  padding-top: 20px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    flex-direction: column;
  }

  .tree-card,
  .video-card {
    height: 50vh;
  }
}

@media (max-width: 768px) {
  .video-monitor-container {
    padding: 10px;
  }

  .toolbar-content {
    flex-direction: column;
    align-items: stretch;
  }

  .toolbar-left,
  .toolbar-right {
    justify-content: center;
  }

  .status-content {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }

  .status-left {
    justify-content: center;
  }

  .status-right {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }

  .header-actions {
    align-self: flex-end;
  }

  .device-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
}
</style>